#include <engine.h>
#include <QCoreApplication>

GAnimate::GAnimate(QEvent::Type type, QGraphicsItem* pItem, QVariant end, double duration)
{
    m_type = type;
    m_pItem = pItem;
    m_end = end;
    m_duration = duration;
}

GAnimate::~GAnimate()
{
}

QGraphicsItem* GAnimate::GetItem()
{
    return m_pItem;
}

QEvent::Type GAnimate::GetType()
{ 
    return m_type;
}

QTime& GAnimate::GetStartTime()
{ 
    return m_startTime;
}

double GAnimate::GetDuration()
{ 
    return m_duration;
}

void GAnimate::SetStart()
{ 
    m_startTime = QTime::currentTime();
    if(m_type == GEvent::Evt_MoveTo)
    {
        m_start = QPoint(m_pItem->x(), m_pItem->y());
    }
    else if(m_type == GEvent::Evt_RotateTo)
    {
        m_start = m_pItem->rotation();
    }
    else if(m_type == GEvent::Evt_ScaleTo)
    {
		m_start = m_pItem->scale();
    }
    else if(m_type == GEvent::Evt_AlphaTo)
    {
		//m_start = m_pItem->alpha();
    }
	else if(m_type == GEvent::Evt_Effect)
	{
		m_start = 0;
	}
}

void GAnimate::DoAnimate(double elapsed)
{
	Q_ASSERT(m_pItem);

    if(m_type == GEvent::Evt_MoveTo)
    {
        QPointF p = bi_lerp(m_start.toPoint(), m_end.toPoint(), elapsed/m_duration);
		//qDebug() << p;
        m_pItem->setPos(p);
    }
    else if(m_type == GEvent::Evt_RotateTo)
    {
        double r = lerp(m_start.toFloat(), m_end.toFloat(), elapsed/m_duration);
        m_pItem->setRotation(r);
    }
	else if(m_type == GEvent::Evt_Effect)
	{
		int nFrame = (int)lerp(m_start.toInt(), m_end.toInt(), elapsed/m_duration);
		GEffect* pEffect = static_cast<GEffect*>(m_pItem);
		pEffect->SetFrame(nFrame);
	}

	//if(!m_pItem->collidingItems(Qt::IntersectsItemShape).isEmpty())
	if(!m_pItem->collidingItems(Qt::ContainsItemShape).isEmpty())
	{
		GObject* pObject = static_cast<GObject*>(m_pItem->toGraphicsObject());
		if(pObject)
			QCoreApplication::instance()->postEvent(pObject, new GEvent(GEvent::Evt_Collision, this));
	}
}

void GAnimate::Finish()
{
	QGraphicsObject* pObject = m_pItem->toGraphicsObject();
	if(pObject == 0)
		pObject = m_pItem->parentObject();

  //  if(m_type == GEvent::Evt_MoveTo)
  //  {
		////QCoreApplication::instance()->postEvent(pObject, new GEvent(GEvent::Evt_MoveTo));
  //  }
  //  else 
	if(m_type == GEvent::Evt_RotateTo)
    {
        m_pItem->setRotation(m_end.toFloat());
        //QCoreApplication::instance()->postEvent(pObject, new GEvent(GEvent::Evt_RotateTo, m_pItem));
    }

	QCoreApplication::instance()->postEvent(pObject, new GEvent(m_type, m_pItem));
}
